﻿using Pomelo.UnityWebSocketPomelo;
using SimpleJson;
using System;
using UnityEngine;

namespace UnityWebSocket.Demo
{
    public class UnityWebSocketDemo : MonoBehaviour
    {
        /// <summary>
        /// pomelo webgl 客户端 
        /// </summary>
        public UnityWebSocketPomeloClient wpClient = null;
        private void Start()
        {
            if (wpClient == null)
            {
                wpClient = new UnityWebSocketPomeloClient(this);
                //监听网络状态变化事件
                wpClient.NetWorkStateChangedEvent += (state) =>
                {
                    Debug.Log("CurrentState is:" + state);
                };

                wpClient.initClient("ws://192.168.22.148:3010/", () =>
                {
                    Debug.Log("wpClient.initClient");
                    //test 握手并登录
                    JsonObject msg = new JsonObject();
                    wpClient.connect(msg, (JsonObject json) =>
                    {
                        Debug.Log("handshakeCallback");
                        JsonObject userMessage = new JsonObject();
                        userMessage["account"] = "123456";
                        userMessage["password"] = "123456";
                        wpClient.request("gate.gateHandler.login", userMessage, OnQuery);
                    });
                });

            }
        }

        void OnQuery(JsonObject result)
        {
            Debug.Log(string.Format("OnQuery {0}", result.ToString()));
            JsonObject data = (JsonObject)result["data"];
            if (Convert.ToInt32(result["code"]) == 200)
            {
                wpClient.disconnect();
                

                string host = (string)data["host"];
                int port = Convert.ToInt32(data["port"]);

                wpClient = new UnityWebSocketPomeloClient(this);
                wpClient.initClient("ws://" + host + ":" + port.ToString() + "/", () =>
                {
                    Debug.Log(string.Format("OnQuery {0} : {1}", host, port));
                    JsonObject msg = new JsonObject();
                    wpClient.connect(msg, (JsonObject json) =>
                    {
                        JsonObject userMessage = new JsonObject();
                        userMessage["token"] = (string)data["token"];
                        if (wpClient != null)
                        {
                            wpClient.request("connector.entryHandler.verifyToken", userMessage, OnEntry);
                        }
                    });
                });
            }
        }

        void OnEntry(JsonObject data)
        {
            Debug.Log(string.Format("OnEntry {0}", data.ToString()));
            //users = data;
            //isLoad = true;
        }

        private void OnApplicationQuit()
        {
            Debug.Log("OnApplicationQuit");
            wpClient.Dispose();
        }

    }
}
